package com.zx.znav.controller.admin;

import com.zx.znav.bean.User;
import com.zx.znav.constant.Constants;
import com.zx.znav.service.UserService;
import com.zx.znav.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec 后台用户登录登出
 * @since 2023-07-18 17:27
 */
@Controller
@RequestMapping("/admin")
public class LoginController {
    @Autowired
    private UserService userService;
    //跳转到登录页面
    @RequestMapping
    public String toLoginPage(){
        return "admin/login";
    }
    //登录
    @PostMapping("/login")
    public String login(String username, String password, HttpSession session, RedirectAttributes attributes){
        //明文加密
        password = MD5Utils.code(password);
        //登录验证
        User user = userService.checkLogin(username, password);
        if(user != null && user.getPassword().equals(password)){
            //这个后台先写的，判断是否是管理员...
            if(!user.getAdmin()){
                attributes.addFlashAttribute(Constants.MESSAGE_KEY, "你没有权限哦");
                return "redirect:/admin";
            }
            user.setPassword(null);
            session.setAttribute(Constants.SESSION_USER_KEY, user);
            return "admin/index";
        }
        attributes.addFlashAttribute(Constants.MESSAGE_KEY, "用户名或密码错误");
        return "redirect:/admin";
    }
    //退出登录
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute(Constants.SESSION_USER_KEY);
        return "redirect:/admin";
    }
}